package com.able.concurrency.t4;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * @author abel.he
 * @data 2018/10/25 15:11
 * @describe CopyOnWriteList 写时复制集合。写入效率低，读取效率高。每次写入数据，都会创建一个新的底层数组。
 */
public class Test2_CopyOnWriteList {

    public static void main(String[] args) {
//        final List<Integer> list = new ArrayList<Integer>();
//        final List<Integer> list = new Vector<Integer>();
        final List<Integer> list = new CopyOnWriteArrayList<Integer>();

        final Random r = new Random(1000000);

        Thread[] threads = new Thread[100];
        final CountDownLatch countDownLatch = new CountDownLatch(threads.length);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000; j++) {
                        list.add(r.nextInt());
                    }
                    countDownLatch.countDown();
                }
            });
        }

        for (Thread thread :
                threads) {
            thread.start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("执行时间： " + (endTime - startTime) + "ms");

    }

}
